<template>
  <div>
    <!-- close:所有的、任意形式的关闭弹窗 -->
    <el-dialog
      :title="info.isAdd ? '添加角色' : '修改角色'"
      :visible.sync="info.isShow"
      width="50%"
      @close="cancel"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="上级分类" prop="pid">
          <el-select v-model="ruleForm.pid" placeholder="请选择">
            <el-option label="顶级分类" :value="0"></el-option>
            <el-option
              v-for="(item, index) in cateList"
              :key="index"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="catename">
          <el-input v-model="ruleForm.catename"></el-input>
        </el-form-item>
        <el-form-item label="分类图片" prop="img">
          <!-- action:上传文件的地址 -->
          <!-- list-type:文件列表的类型，有文字类型的，有照片墙的 -->
          <!-- on-remove：移除图片时调用的函数 -->
          <!-- on-change：文件状态改变时的钩子 -->
          <el-upload
            action="#"
            list-type="picture-card"
            :on-change="handleChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="1"
            :on-exceed="limitImg"
          >
            <!-- :on-preview="handlePictureCardPreview" -->
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="imgUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCatelistTree, cateAdd, cateEdit } from "../../request";
// 弹窗的默认值
let defaultData = {
  pid: 0,
  catename: "",
  img: "",
  status: 1,
};
export default {
  props: {
    info: {
      type: Object,
      default: {
        isAdd: false,
        isShow: false,
      },
    },
  },
  data() {
    return {
      // 表单的数据
      ruleForm: {
        pid: 0,
        catename: "",
        img: "",
        status: 1,
      },
      // 表单的规则
      rules: {
        catename: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        pid: [{ required: true, message: "请选择上级分类", trigger: "blur" }],
      },
      // 下拉菜单的数据
      cateList: [],
      dialogVisible: false,
      imgUrl: "",
      fileList: [], //初始化一个空数组,上传文件列表
    };
  },
  created() {
    // 获取分类列表
    this.getList();
  },
  methods: {
    // 修改文件时触发
    handleChange(file, fileList) {
      // 给img赋值，传给fd
      this.ruleForm.img = fileList[0].raw;
    },
    // handlePictureCardPreview() {
    //   // 预览事件
    //   this.imgUrl = file.url;
    //   this.dialogVisible = true;
    // },
    // 删除图片的监听
    handleRemove() {
      this.ruleForm.img = "";
    },
    limitImg() {
      this.$message.warning("分类图片最多添加一张");
    },
    async getList() {
      let res = await getCatelistTree();
      this.cateList = res.list;
    },
    // 设置当前组件状态
    setStatus(val) {
      this.ruleForm = { ...val };
      // 二级分类有图片，需要显示出来
      if (this.ruleForm.img) {
        this.fileList.push({
          name: "小U商城",
          url: this.$host + this.ruleForm.img,
        });
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 创建FormData对象，赋值成功后将这个数据传给后台
          let fd = new FormData();
          // 给FormData赋值的方式：fd.append('name', 'jack')
          this.ruleForm.children ? delete this.ruleForm.children : "";
          for (let k in this.ruleForm) {
            // 遍历对象，将this.ruleForm的值传给fd
            fd.append(k, this.ruleForm[k]);
          }
          // 查看fd数据的方式
          // fd.forEach((key, val) => {
          //   console.log(key, val);
          // })
          // 封装请求
          let res;
          if (this.info.isAdd) {
            res = cateAdd(fd);
          } else {
            res = cateEdit(fd);
          }
          if (res) {
            this.cancel();
            // 兄弟组件传值，告诉list组件更新数据
            this.$bus.$emit("update");
          }
        } else {
          return false;
        }
      });
    },
    // 点击取消，清空数据
    cancel() {
      // 重置弹窗中的数据
      this.ruleForm = { ...defaultData };
      // 清理文件列表
      this.fileList = [];
      // 关闭弹窗
      this.info.isShow = false;
    },
  },
};
</script>

<style>
</style>